package com.david.func_test.util

import android.app.Application
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.widget.Toast
import androidx.documentfile.provider.DocumentFile
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

object ImFileUtil {

    private lateinit var applicationContext: Context

    fun init(context: Context) {
        applicationContext = context
        File(applicationContext.cacheDir.absolutePath + "/im/").mkdirs()
    }

    fun copyFileToCache(context: Application, uri: Uri){
        copyFileToCache(context, uri, null)
    }

    fun copyFileToCache(context: Context, uri: Uri, onFileCopiedListener:OnFileCopiedListener?){
        val name = getUriName(uri)
        val absolutePath = applicationContext.cacheDir.absolutePath + "/im/" + name
        if (File(absolutePath).exists()) {
            Toast.makeText(context, "文件已添加过", Toast.LENGTH_LONG).show()
            onFileCopiedListener?.onCopyFailed(absolutePath, "文件已添加过")
            return
        }
        CoroutineScope(Dispatchers.IO).launch {
            writeCacheFile(context, uri)
            onFileCopiedListener?.onFileCopy(name, absolutePath)
        }
    }

    fun writeCacheFile(context: Context, uri: Uri){
        val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
        inputStream?.apply {
            val name = getUriName(uri)
            val file = File(applicationContext.cacheDir.absolutePath + "/im/" + name)
            if (!file.exists()) {
                val fos = FileOutputStream(file)
                val bytes = ByteArray(512)
                var length = inputStream.read(bytes)
                while (length > 0) {
                    fos.write(bytes, 0, length)
                    fos.flush()
                    length = inputStream.read(bytes, 0, length)
                }
                inputStream.close()
                fos.close()
            }
        }
    }

    fun getUriName(uri: Uri): String {
        return if (!TextUtils.isEmpty(uri.path) && uri.path!!.contains(".")) {
            val name = uri.path?.substring(
                uri.path!!.lastIndexOf("/") + 1)

            name!!
        } else {
            getFileRealNameFromUri(uri)!!
        }

    }

    /**
     * 获取app中缓存的文件路径
     */
    fun getDocCachePath(name: String):String{
        return applicationContext.cacheDir.absolutePath + "/im/" + name
    }


    fun getFileRealNameFromUri(fileUri: Uri?): String? {
        if (fileUri == null) return null
        val documentFile = DocumentFile.fromSingleUri(applicationContext, fileUri) ?: return null
        return documentFile.name
    }
}

interface OnFileCopiedListener{
    fun onFileCopy(name:String, path:String)
    fun onCopyFailed(path:String, msg: String)
}